//index.js
//获取应用实例
const app = getApp()
var util = require('../../utils/util');
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    longitude: 114.34253,
    latitude: 30.49984,
    portrait_photo: "",
    isShow: false,
    imageUrl: "",
    qid: "",
    match: "",
    PageIndex: 1,
    ListWithdrawals: [],
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  closePay: function () {
    this.setData({
      isShow: false
    })
  },
  previewImg: function (e) {
    var arr = [];
    var id = e.currentTarget.dataset.id;
    var list = this.data.ListWithdrawals;
    for (var i = 0; i < list.length; i++) {
      var item = list[i];
      if(item._id == id){
        arr = item.photos;
        break;
      }
    }
    var index=e.currentTarget.dataset.order;
    wx.previewImage({
      current: arr[index],
      urls: arr,
    });
  },
  inputMatch: function(e){
    var val = e.detail.value;
    this.setData({
      match: val
    })
  },
  searchData: function(){
    this.setData({
      PageIndex: 1,
      ListWithdrawals: []
    })
    this.listStatics();
  },
  praise: function (e) {
    var _this = this;
    var qid = e.target.dataset.qid;
    var listWithdrawals = _this.data.ListWithdrawals;
    util.requrest("api/home/praise", {
      uid: app.globalData.userInfo.uid,
      token: app.globalData.userInfo.token,
      obj_id: qid,
      answer_id: '',
      praise: 1,
      critique: 0
    }, function (data) {
      if (data.type == 1) {
        for (var i = 0; i < listWithdrawals.length; i++){
          var item = listWithdrawals[i];
          if(item._id == qid){
            item.praise++;
            break;
          }
        }

        _this.setData({
          ListWithdrawals: listWithdrawals
        })
      } else {
        app.showMsg(data.message);
      }
    })
  },
  listStatics: function () {
    var _this = this;
    util.requrest("api/home/index", {
      token: app.globalData.userInfo.token,
      page: _this.data.PageIndex,
      pagesize: 20,
      match: _this.data.match
    }, function (data) {
      console.log(data)
      if (data.type == 1) {
        var now = data.message;
        var list=[];
        list = data.resultdata;
        for (var i = 0; i < list.length; i++){
          var gps = list[i].content.replace("GPS:", "");
          var arr = gps.split('@');
          var longitude = _this.data.longitude;
          var latitude = _this.data.latitude;
          var result = _this.getDistance(longitude, latitude, parseFloat(arr[0]), parseFloat(arr[1]));
          list[i].content = result;
          var hourArr = _this.timeFn(now, list[i].close_at).split('|');
          list[i].dayDiff = hourArr[0];
          list[i].hours = hourArr[1];
          // list[i].create_at = list[i].create_at.substr(0, 13);
          list[i].create_at = util.formatDate(now, list[i].create_at);
          // if(i===0){
          //   console.log(list[i]._create_tm, util.formatDate(list[i]._create_tm));
          // }
          if (list[i].portrait_photo.indexOf("null") != -1){
            list[i].portrait_photo = '../../images/icon-user-default.png';
          }
          var photos = list[i].photos;
          if (photos != undefined){
            for (var j = 0; j < photos.length; j++) {
              photos[j] = "http://p2sqrzuvl.bkt.clouddn.com/" + photos[j];
            }
          }
          var isMyQuestion = false;
          if (app.globalData.user.uid == list[i].author_id) {
            isMyQuestion = true;
          }
          list[i].author_name = app.maskName(list[i].author_name, isMyQuestion);
          _this.data.anscount = 0;
          _this.partakeCount(list[i].answer);
          list[i].anscount = _this.data.anscount;
        }
        var staticsPageList = _this.data.ListWithdrawals;
        _this.setData({
          ListWithdrawals: staticsPageList.concat(list)
        });
      }
    })
  },
  partakeCount: function (answer){
    var count = 0;
    if (answer != undefined){
      this.data.anscount += answer.length;
      for(var i = 0; i < answer.length; i++){
        this.partakeCount(answer[i].answer);
      }
    }
  },
  timeFn: function (d1, source) {//di作为一个变量传进来
    //如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
    var dateBegin = new Date(d1.replace(/-/g, "/"));//将-转化为/，使用new Date
    var dateEnd = new Date(source.replace(/-/g, "/"));//获取当前时间
    var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
    var leave1 = dateDiff % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000)    //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000);
    if (dayDiff < 0 || hours < 0){
      dayDiff = "-";
      hours = "-";
    }
    return dayDiff + "|" + hours;
  },
  getDistance: function (lat1, lng1, lat2, lng2) {
    var result = "";

    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;

    if (lat1 == 0 || lng1 == 0 || lat2 == 0 || lng2 == 0){
      return result;
    }

    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

    var r = 6378137;
    var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

    if (distance < 1000){
      result = parseInt(distance) + "m";
    }else{
      result = Math.round(distance / 1000).toFixed(1) + "km";
    }
    return result;
  },
  //获取当前位置的经纬度
  loadInfo: function () {
    var _this = this;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        var longitude = res.longitude//经度
        var latitude = res.latitude//维度
        _this.setData({
          longitude: longitude,
          latitude: latitude
        })
      }
    })
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    wx.hideShareMenu();
    this.loadInfo();
    if (!app.globalData.userInfo){
      wx.navigateTo({
        url: '../login/login'
      })
      return;
    }
    this.listStatics();
    this.setData({
      portrait_photo: app.globalData.user.portrait_photo
    })
    return;

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo;
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e);
    app.globalData.userInfo = e.detail.userInfo;
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      PageIndex: 1,
      ListWithdrawals: []
    })
    this.listStatics();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var PageIndex = this.data.PageIndex;
    PageIndex++;
    this.setData({
      PageIndex: PageIndex,
      match: ""
    })
    this.listStatics();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var _this=this;
    // console.log(getCurrentPages());
    // console.log(this.route);  // 到当前页面的路径，类型为String。
    wx.setStorage({
      key:"routePage",
      data:_this.route
    });
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },
  startShare: function (e) {
    var _this = this;
    var imgurl = app.globalData.user.portrait_photo;
    var content = e.target.dataset.title;
    var money = e.target.dataset.money;
    var qid = e.target.dataset.qid;
    var url = "api/home/createShareFile?imgurl=" + imgurl + "&content=" + content + "&money=" + money;
    util.requrest(url, {}, function (result) {
      if (result.type == 1) {
        var imageUrl = result.resultdata;
        _this.setData({
          imageUrl: imageUrl,
          qid: qid,
          isShow: true
        })
      }
    })
  },
  onShareAppMessage: function (e) {
    var _this = this;
    _this.setData({
      isShow: false
    })
    var photo = app.globalData.user.portrait_photo;
    var uid = app.globalData.userInfo.uid;
    return {
      imageUrl: _this.data.imageUrl,
      path: 'pages/questionDetail/questionDetail?id=' + _this.data.qid + "," + uid + "," + photo, // 路径，传递参数到指定页面。
      success: function () {
        console.log("1111")
      },
      fail: function () {
        console.log("2222")
      }
    }
  }
})